# Maintainer: Martell Malone <martellmalone@gmail.com>

_realname=luajit
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
# LuaJIT has abandoned versioned releases and now advises using git HEAD
# https://github.com/LuaJIT/LuaJIT/issues/665#issuecomment-784452583
_commit="51fb2f2c3af778f03258fccee9092401ee4a0215"
pkgver=2.1.0.beta3.r481.g51fb2f2c
pkgrel=3
pkgdesc="Just-in-time compiler and drop-in replacement for Lua 5.1 (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://luajit.org/"
license=('spdx:MIT')
conflicts=("${MINGW_PACKAGE_PREFIX}-lua51"
           "${MINGW_PACKAGE_PREFIX}-luajit-git")
provides=("${MINGW_PACKAGE_PREFIX}-lua51"
          "${MINGW_PACKAGE_PREFIX}-luajit-git")
replaces=("${MINGW_PACKAGE_PREFIX}-lua51"
          "${MINGW_PACKAGE_PREFIX}-luajit-git")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc" "git")
source=("${_realname}"::"git+https://luajit.org/git/luajit.git#commit=${_commit}"
        001-mintty-cygpty-isatty.patch
        002-fix-pkg-config-file.patch
        003-lua51-modules-paths.patch
        004-fix-default-cc.patch)
sha256sums=('SKIP'
            '0cadf1b6c67c910c81ccb7a6152148dccfb0f1c6b50cdb09a5707cd45e7cbe85'
            '4df486e82b0bbeead01dcf6001e90c51477a3a8ac18611d60d7067f2c7013428'
            'b8c9c9c6e16f8c772f760a9e2f39c048ca00dea01c7b7699f1dbe90e93f2c26c'
            '444df1c8ab9c8c348c7c81a7a6bf15d7e02410f4edc38894a65a4bb7ee9a8d68')

pkgver() {
  cd "${_realname}"
  git describe --long "${_commit}" | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/^v//g'
}

prepare() {
  cd "${_realname}"
  rm -f src/iscygpty.{c,h} || true
  git apply ${srcdir}/001-mintty-cygpty-isatty.patch
  git apply ${srcdir}/002-fix-pkg-config-file.patch
  git apply ${srcdir}/003-lua51-modules-paths.patch
  git apply ${srcdir}/004-fix-default-cc.patch
  sed -i "s|export PREFIX= /usr/local|export PREFIX="${MINGW_PREFIX}"|g" ${srcdir}/${_realname}/Makefile
}

build() {
  cd "${_realname}"

  XCFLAGS=-DLUAJIT_ENABLE_GC64
  if [[ "$MSYSTEM" == "MINGW32" || "$MSYSTEM" == "CLANG32" ]]; then
    # https://github.com/msys2/MINGW-packages/issues/17042
    XCFLAGS+=" -DLUAJIT_NO_UNWIND"
  fi

  msg "Build static version"
  make amalg BUILDMODE=static XCFLAGS="${XCFLAGS}"

  msg "Build dynamic version"
  make XCFLAGS="${XCFLAGS}"
}

package() {
  cd "${_realname}"
  make DESTDIR=${pkgdir} install

  install -v -Dm644 "${srcdir}/${_realname}/src/lua51.dll" "${pkgdir}${MINGW_PREFIX}/bin/lua51.dll" || exit 1
  install -v -Dm644 "${srcdir}/${_realname}/src/luajit.exe" "${pkgdir}${MINGW_PREFIX}/bin/luajit.exe" || exit 1
  install -v -Dm644 "${srcdir}/${_realname}/src/libluajit-5.1.dll.a" "${pkgdir}${MINGW_PREFIX}/lib/libluajit-5.1.dll.a" || exit 1

  cp ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/lua{jit,5.1}.pc
}
